package chapter9.javaFile.NIO;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestFile {

	public static void main(String[] args) {

		// Creando un fichero
		File file = new File("ficheroMAC.txt");
		System.out.println("El fichero existe: " + file.exists());
		System.out.println("Es un directorio:" + file.isDirectory());
		System.out.println("Es un fichero: " + file.isFile());
		System.out.println("Abosulte path: " + file.getAbsolutePath());
		try {
			System.out.println("El fichero ha sido creado: "
					+ file.createNewFile());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Escribiendo en un fichero
		FileWriter fw = null;
		PrintWriter pw = null; // Uso PrintWriter en vez de BufferedWriter
		try {
			fw = new FileWriter(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			pw = new PrintWriter(file);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		pw.println("línea nueva");
		pw.println("linea nueva 2");
		pw.println(false);
		pw.print(new Object());
		pw.flush();// Es necesario realizar el flush xq puede ocurrir un
					// StreamException
		pw.close();

		// Leyendo de un fichero
		FileReader fr = null;
		try {
			fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		BufferedReader bf = new BufferedReader(fr);
		try {
			String linea;
			while ((linea = bf.readLine()) != null) {
				System.out.println(linea);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			fr.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			bf.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
